package com.maotouying.owlsmart.LoginPage;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maotouying.owlsmart.MainPage.FragmentManagerActivity;
import com.maotouying.owlsmart.R;
import com.maotouying.owlsmart.SmartLayout.tdialog.TDialog;
import com.maotouying.owlsmart.SmartLayout.tdialog.base.BindViewHolder;
import com.maotouying.owlsmart.SmartLayout.tdialog.base.TBaseAdapter;
import com.maotouying.owlsmart.SmartLayout.tdialog.list.TListDialog;
import com.maotouying.owlsmart.SmartUtil.Http.localSqlite;
import com.maotouying.owlsmart.SmartUtil.md5.MD5Util;
import com.maotouying.owlsmart.SmartUtil.md5.md5Encrypt;
import com.maotouying.owlsmart.SmartUtil.Http.portPath;
import com.maotouying.owlsmart.SmartUtil.Sqlite.DatabaseHelper;
import com.maotouying.owlsmart.SmartUtil.Sqlite.dbUtil;
import com.maotouying.owlsmart.SmartUtil.SystemUtil;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
//登录页面
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView go_register,go_owlweb,go_forget;

    private EditText et_username,et_password;

    private LinearLayout btn_login;

    private String loginPath = "/owl/user/login.do";
    private String smartPath;
    private String userInfo,userArrayList,userPresent;//数据库获取的用户信息
    private SQLiteDatabase db;
    private DatabaseHelper helper;
    private md5Encrypt md5;
    private dbUtil delete_table;
    private ImageView show_hidden;
    boolean isChanged = false;
    private ImageView clean_edit,clean_edituser,iv_userlist;
    private Vibrator mVibrator;  //声明一个振动器对象

    private String tempusername="",temppassword="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        SystemUtil.setStatusBarColor(this, this.getResources().getColor(R.color.top_background_color));

        //初始化数据库
        initsqlite();

        //初始化页面
        InitView();


        //测试调用，删除一个库，新建用
//        {
//
//            dbUtil dbase =  new dbUtil();
//            dbase.deleteDatabase(LoginActivity.this,"db_owlsmart");
//        }

        //拿到Address根地址
        portPath port = new portPath();
        smartPath = port.getPath(LoginActivity.this);

        //获取数据库数据
        localSqlite user= new localSqlite();
        userInfo = user.getUserinfo(LoginActivity.this);
        userArrayList = user.getUserArray(LoginActivity.this);
        userPresent  = user.getPresent(LoginActivity.this);


        System.out.println("临时表:::"+userPresent);
        System.out.println("用户表:::"+userArrayList);
        //拿到注册过来的邮箱密码
        Intent intent=getIntent();
        String activity=intent.getStringExtra("activity");
        String email=intent.getStringExtra("email");
        String password=intent.getStringExtra("password");

        //判断是否有数据，有数据就充填
        if("SigninActivity".equals(activity)){

            et_username.setText(email);
            et_password.setText(password);

        }else {
               if(user.UserDatamount()==1) {
                //充填登录页面数据
                et_username.setText(userInfo.split("#")[0]);
                et_password.setText(userInfo.split("#")[1]);
                //更换头像为列表(细节拉满)
                iv_userlist.setImageDrawable(getResources().getDrawable(R.drawable.ic_userlist));
                iv_userlist.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //解析userArrayList
                        //System.out.println("userArrayList::"+userArrayList);
//                        if(userArrayList.contains("},{")){

                            JSONArray jsArr = JSONObject.parseArray(userArrayList);
                            List<String> list = JSONObject.parseArray(jsArr.toJSONString(), String.class);

                            localuserList(list);
//                        }else {
//                            Toast.makeText(LoginActivity.this, "没有更多用户", Toast.LENGTH_LONG).show();
//
//                        }
                    }
                });
            }else {
                   btn_login.setBackground(getResources().getDrawable(R.drawable.round_corner_default));
               }
        }

    }


    private void InitView(){

        mVibrator = (Vibrator) getApplication().getSystemService(Service.VIBRATOR_SERVICE);//震动
        et_username = (EditText)findViewById(R.id.et_username);//用户名和邮箱
        et_password = (EditText)findViewById(R.id.et_password);
        btn_login = (LinearLayout) findViewById(R.id.btn_login);
        show_hidden = (ImageView) findViewById(R.id.show_hidden);
        go_forget= (TextView) findViewById(R.id.go_forget);
        clean_edit= (ImageView) findViewById(R.id.clean_edit);
        clean_edituser= (ImageView) findViewById(R.id.clean_edituser);
        go_owlweb= (TextView) findViewById(R.id.go_owlweb);
        go_register = (TextView)findViewById(R.id.go_register);
        iv_userlist= (ImageView) findViewById(R.id.iv_userlist);
        et_username.setImeOptions(EditorInfo.IME_FLAG_NAVIGATE_NEXT);
        et_username.setSingleLine();

        go_forget.setOnClickListener(this);
        go_owlweb.setOnClickListener(this);
        clean_edit.setOnClickListener(this);
        clean_edituser.setOnClickListener(this);
        go_register.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        show_hidden.setOnClickListener(this);
        iv_userlist.setOnClickListener(this);

        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                loginBtnState();
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                loginBtnState();
            }
            @Override
            public void afterTextChanged(Editable s) {
                loginBtnState();
            }
        });

    }

    //设置登录，情况，显示隐藏控件的显示与隐藏
    private void loginBtnState(){

        if(et_password.getText().toString().equals("")){
            btn_login.setBackground(getResources().getDrawable(R.drawable.round_corner_default));
            clean_edit.setVisibility(View.INVISIBLE);
            show_hidden.setVisibility(View.INVISIBLE);
        }else {
            btn_login.setBackground(getResources().getDrawable(R.drawable.round_corner));
            clean_edit.setVisibility(View.VISIBLE);
            show_hidden.setVisibility(View.VISIBLE);
        }
    }


    public void initsqlite() {
        helper = new DatabaseHelper(this, "db_owlsmart", null, R.string.db_version);//dbName数据库名
        db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
    }

    public void postTest(String email, String password){
        md5 = new md5Encrypt();
        OkHttpClient client = new OkHttpClient();
        //post请求
        FormBody formBody = new FormBody.Builder()
                .add("email",email)
                .add("password",md5.toMd5(password))
                .build();

        Request request = new Request.Builder().url(smartPath+loginPath).post(formBody).build();

        client.newCall(request).enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }

            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                    String result = response.body().string();
                    System.out.println(result);

                    JSONObject code = JSONObject.parseObject(result);
                    int status = code.getInteger("status");
                    if(status==0){
                        //写入数据库
                        String data = code.getString("data");
                        Message msg = new Message();
                        msg.what = 16;
                        Bundle bundle = new Bundle();
                        bundle.putString("result", data);
                        msg.setData(bundle);
                        Thandler.sendMessage(msg);
                    }else {
                        String msgHint = code.getString("msg");
                        Message msg = new Message();
                        msg.what = 22;
                        Bundle bundle = new Bundle();
                        bundle.putString("msgHint", msgHint);
                        msg.setData(bundle);
                        Thandler.sendMessage(msg);
                    }


                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        Intent intent;
        switch (id) {
            case R.id.go_forget:
                intent = new Intent(LoginActivity.this, ForgetActivity.class);
                startActivity(intent);
                break;
            case R.id.go_owlweb:
                Uri uri = Uri.parse("http://www.owlsmart.net");
                intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                break;
            case R.id.clean_edit:
                et_password.setText("");
                break;
            case R.id.clean_edituser:
                et_username.setText("");
                break;
            case R.id.go_register:
                intent = new Intent(LoginActivity.this, SigninActivity.class);
                startActivity(intent);
                break;
            case R.id.show_hidden:
                if (v == show_hidden) {
                    if (isChanged) {
                        show_hidden.setImageDrawable(getResources().getDrawable(R.drawable.invisible_default_icon));
                        // 隐藏密码
                        et_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    } else {
                        show_hidden.setImageDrawable(getResources().getDrawable(R.drawable.invisible_highlight_icon));
                        //显示密码
                        et_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    }
                    isChanged = !isChanged;
                }
                break;
            case R.id.btn_login:
                //点击登录
                String username =  et_username.getText().toString();
                String password = et_password.getText().toString();
                if(username.isEmpty()|password.isEmpty()){
                    Toast.makeText(LoginActivity.this, "用户名/密码不能为空", Toast.LENGTH_SHORT).show();
                    //错误就震动一下
                    mVibrator.vibrate(100);
                }else {

                    System.out.println("username::"+username);
                    System.out.println("password::"+password);

//                    if(!tempusername.equals(username)|!temppassword.equals(password)){
                        postTest(username,password);

//                    }else {
//                        mVibrator.vibrate(100);
//                        et_password.setText("");
//                    }
                }
                break;

        }
    }


    private Handler Thandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 16:
                    String result = msg.getData().getString("result");//接受msg传递过来的参数
                    System.out.println("Handler::::"+result);
                    //这里操作更新ui
                    JSONObject content = JSONObject.parseObject(result);
                    String owlId = content.getString("owlId");
                    String username = content.getString("username");
                   // String password = content.getString("password");
                    String email = content.getString("email");
                    String phone = content.getString("phone");
                    String token = content.getString("token");
                    String userProfileImage = content.getString("userProfileImage");

                    //写入之前先清空，只需要保证presentTable当前用户表只有一个数据
                    Log.i("System.out------", "已经存在,刷新之前的");

                     dbUtil dbase =  new dbUtil();
                     dbase.deleteTable( db ,"presentTable");

                    localSqlite ls =  new localSqlite();

                {
                    //获取到的数据存入数据库
                    ContentValues valuedown = new ContentValues();
                    // 开始组装第一条数据
                    valuedown.put("token", token);
                    valuedown.put("owlId", owlId);
                    valuedown.put("username", username);
                    valuedown.put("password", et_password.getText().toString());
                    valuedown.put("email", email);
                    valuedown.put("phone", phone);
                    valuedown.put("userProfileImage", userProfileImage);
                    // 当前用户表刷新数据
                    db.insert("presentTable", null, valuedown);
                    // 用户列表插入一条数据

                    if(!ls.getUserArray(LoginActivity.this).contains(email)) {
                        db.insert("userTable", null, valuedown);
                        System.out.println("用户列表插入一条数据::::" + username);
                    }

                    valuedown.clear();
                    db.close();
                }

                    Intent intent = new Intent(LoginActivity.this, FragmentManagerActivity.class);
                    startActivity(intent);
                    finish();
                    break;

                case 22:

                    String msgHint = msg.getData().getString("msgHint");//接受msg传递过来的参数
                    System.out.println("Handler::::"+msgHint);

                        //错误就震动一下
                        mVibrator.vibrate(100);
                        //为了防止重复点击，将账号密码存储起来，再次请求先判断账号密码是否有修改，没有修改，就多震动一会儿
                        tempusername = et_username.getText().toString();
                        temppassword = et_password.getText().toString();

                    break;


            }
        }
    };




    public void localuserList(List<String> list) {

        new TListDialog.Builder(getSupportFragmentManager())
                .setScreenHeightAspect(this, 0.3f)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.BOTTOM)
                .setAdapter(new TBaseAdapter<String>(R.layout.item_localuser, list) {
                    @Override
                    protected void onBind(BindViewHolder holder, int position, String s) {

                        JSONObject data_key = JSONObject.parseObject(s);
                        String email = data_key.getString("email");
                        holder.setText(R.id.tv, email);

                    }
                })
                .setOnAdapterItemClickListener(new TBaseAdapter.OnAdapterItemClickListener<String>() {
                    @Override
                    public void onItemClick(BindViewHolder holder, int position, String s, TDialog tDialog) {
                        Toast.makeText(LoginActivity.this, "click:" + s, Toast.LENGTH_SHORT).show();
                        JSONObject data_key = JSONObject.parseObject(s);
                        String email = data_key.getString("email");
                        String password = data_key.getString("password");

                        et_username.setText(email);
                        et_password.setText(password);

                        tDialog.dismiss();
                    }
                })
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                       // Toast.makeText(LoginActivity.this, "setOnDismissListener 回调", Toast.LENGTH_SHORT).show();
                    }
                })
                .create()
                .show();


    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
        if(keyCode== KeyEvent.KEYCODE_BACK)
            return true;
        return super.onKeyDown(keyCode, event);
    }//屏蔽返回键
}